package com.edu.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.edu.bean.User;
import com.edu.service.UserService;
import com.edu.service.impl.UserServiceImpl;
@WebServlet("/updateusers.do")
@MultipartConfig
public class UpdateUsersServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		UserService us = new UserServiceImpl();
		String id = req.getParameter("userid"); 
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String sex = req.getParameter("sex");
		String realname = req.getParameter("realname");
		String email = req.getParameter("email");
		String telephone = req.getParameter("telephone");
		String idNum = req.getParameter("idNum");
		int userid = Integer.parseInt(id);
		User user = new User(userid,username,password,sex,realname,email,telephone,idNum);
		//获取用户上传的文件
		Part part = req.getPart("headimg");
		//用户只能上传小于1M的图片，且必须上传
		boolean headimg=false;
		String savePath="";
		if(part.getSize() > 0 ) {
			if(part.getSize() <=1024*1024 || part.getContentType().contains("image")) {
				//生成一个独一无二的文件名.UUID，用户名_时间戳_原始文件名
				String saveName = username+"_"+System.currentTimeMillis()+part.getSubmittedFileName();
				//把文件存储到服务器的headImg路径下（真实路径）
				savePath = "c:/car/headImgs/"+saveName;
				//访问路径存在数据库，取出来之后直接拼字img下面的src的路径下
				String visitPath = "/PhaetonCommunity/headImgs/"+saveName;
				//用户上传的文件需要复制到真实保存路径
				part.write(savePath);
				user.setHeadimg(visitPath);
				headimg=true;
			}else {
				req.setAttribute("bookImgMsg","图片必须小于1m");
				return;
			}
		}
		int res = us.updateUser(user);
		if(res == 1 && headimg) {
			String oldheadimg=req.getParameter("oldheadimg");
			if(!"/PhaetonCommunity/headImgs/mrtp.jpg".equals(oldheadimg)) {
				String[] strs=oldheadimg.split("/");
				String fileName=strs[strs.length-1];
				File file=new File("C:/PhaetonCommunityImg/headImgs/"+fileName);
				if(file.exists()) {
					file.delete();
				}
			}
		}
	}
}
